package com.retail.bbq.cola.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.retail.bbq.cola.enums.ErrorCodeEnum;
import com.retail.bbq.cola.exception.BusinessException;
import com.retail.bbq.cola.feign.LawsonFeign;
import com.retail.bbq.cola.service.LawsonService;
import com.retail.bbq.cola.vo.request.LawsonSyncMemberRequest;
import com.retail.bbq.cola.vo.response.LawsonSyncMemberResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author : jie.zhou
 * @date : 2025/7/17
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LawsonServiceImpl implements LawsonService {

    private final LawsonFeign lawsonFeign;

    @Value("${lawson.organizationId}")
    private String organizationId;

    @Override
    public LawsonSyncMemberResponse syncMember(LawsonSyncMemberRequest request) {
        if (StringUtils.isEmpty(request.getOrgUserId()) || StringUtils.isEmpty(request.getUserId())) {
            log.error("参数错误: orgUserId: {}, userId: {}", request.getOrgUserId(), request.getUserId());
            throw new BusinessException(ErrorCodeEnum.PARAM_ERROR);
        }
        String timestamp = System.currentTimeMillis() + "";
        request.setOrganizationId(organizationId);
        TreeMap<String, Object> treeMap = JSONObject.parseObject(JSONObject.toJSONString(request), new TypeReference<TreeMap<String, Object>>() {
        });
        treeMap.put("timestamp", timestamp);
        String signature = sign(treeMap);
        return lawsonFeign.syncMember(request, signature, timestamp);
    }

    private String sign(TreeMap<String, Object> treeMap) {
        String content = treeMap.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        try {
            return sign(content);
        } catch (NoSuchAlgorithmException e) {
            throw new BusinessException(ErrorCodeEnum.SIGN_GENERATION_FAIL);
        }
    }

    private String sign(String content) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] encodedhash =
                digest.digest(content.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(encodedhash);
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
